package ru.osu.acm.testing.beans;

import ru.osu.acm.common.config.Config;
import ru.osu.acm.common.industrial.ProblemFactory;
import ru.osu.acm.common.industrial.CheckerFactory;
import ru.osu.acm.common.entities.Problem;
import ru.osu.acm.common.entities.Checker;
import ru.osu.acm.testing.Utils;

import javax.annotation.Resource;
import javax.sql.DataSource;
import javax.faces.model.SelectItem;
import java.util.ArrayList;

/**
 * User: aleksey
 * Date: Sep 25, 2009
 * Time: 8:14:39 PM
 */
public class ProblemBean {
    @Resource(name = Config.jndi)
    private DataSource source;

    public ArrayList<Problem> getProblems() {
        return ProblemFactory.getAllProblems(Utils.getConnection(source), true);
    }

    private Problem viewingProblem = null;

    public Problem getViewingProblem() {
        return viewingProblem;
    }

    private Problem editingProblem = null;

    public Problem getEditingProblem() {
        return editingProblem;
    }

    public ArrayList<SelectItem> getAllCheckers() {
        ArrayList<SelectItem> items = new ArrayList<SelectItem>();
        ArrayList<Checker> checkers = CheckerFactory.getAllCheckers(Utils.getConnection(source), true);
        for (Checker checker : checkers) {
            items.add(new SelectItem(checker.getId(), "[" + checker.getId() + "] " + checker.getFilename()));
        }
        return items;
    }

    // Action handlers

    public String viewProblem() {
        viewingProblem = ProblemFactory.getProblem(Integer.parseInt(Utils.getRequestParam("problem")), Utils.getConnection(source), true);
        String index = Utils.getRequestParam("index");
        if (index.length() > 0) {
            viewingProblem.setIndex(Integer.parseInt(index));
        }
        return "problem_viewer";
    }

    public String editProblem() {
        editingProblem = ProblemFactory.getProblem(Integer.parseInt(Utils.getRequestParam("problem")), Utils.getConnection(source), true);
        return "problem_editor";
    }

    public String createProblem() {
        editingProblem = ProblemFactory.getNewProblem(Utils.getConnection(source), true);
        return "problem_editor";
    }

    public String saveProblem() {
        ProblemFactory.updateProblem(editingProblem, Utils.getConnection(source), true);
        editingProblem = ProblemFactory.getProblem(editingProblem.getId(), Utils.getConnection(source), true);
        return null;
    }
}
